const Elastic = require('../models/elastic')
const Behavior = require('../models/behavior')

module.exports.list = async (ctx, next) => {
	const query = ctx.query
	const results = await Elastic.list(query)
	Behavior.save({
		actor: query.finger,
		verb: 'search',
		content: query.q,
		key: query.q
	})
	ctx.response.body = results
}

module.exports.hit = async(ctx, next) => {
	const param = ctx.request.body
	const user = ctx.state.user
	const result = await Elastic.hit(param.course._id, user)
	Behavior.save(constBehavior(param, 'hit'))
	ctx.response.body = result
}
module.exports.bookmark = async(ctx, next) => {
	const param = ctx.request.body
	const result = await Elastic.bookmark(param.course._id)
	Behavior.save(constBehavior(param, 'bookmark'))
	ctx.response.body = result
}
module.exports.share = async(ctx, next) => {
	const param = ctx.request.body
	const result = await Elastic.share(param.course._id)
	Behavior.save(constBehavior(param, 'share'))
	ctx.response.body = result
}

module.exports.recomms = async (ctx, next) => {
	const recomms = await Elastic.findRecomms()
	ctx.response.body = recomms
}

function constBehavior(param, verb) {
	return {
		actor: param.finger,
		verb,
		content: param.course.title,
		key: param.course._id
	}
}